#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import re
import ctypes
import locale
import subprocess
from PyQt4 import QtGui
from urllib import URLopener
from urllib2 import urlopen
from xml.dom.minidom import parseString

def main(env):
	extensions = [""]
	if env["context"]["selection"] == "":
		try:
			rss_contents = urlopen(env["static"]["cwWallPaper_rssFeed"])
		except:
			return [("messageBox",env["static"]["cwWallPaper_rssFailedMessage"] % url)]
		dom = parseString(rss_contents.read())
		firstitem = dom.getElementsByTagName('item')[0]
		link = firstitem.getElementsByTagName('enclosure')[0].getAttribute('url')
		stagingPath = os.path.normpath(os.path.join(env["meta"]["path"], "desktopImage.jpg"))
		URLopener().retrieve(link, stagingPath)
	else:
		basePath = os.path.expanduser(env["prefs"]["cwWallPaper_baseDirectory"])
		if basePath == "":
			basePath = unicode(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.PicturesLocation))
		stagingPath = os.path.join(basePath, unicode(env["context"]["selection"]).rstrip())
		extensions.extend(["."+s for s in re.split(r"\W+",env["prefs"]["cwWallPaper_defaultExtensions"].strip())])
	paths = ["%s%s" % (os.path.normpath(stagingPath),extension) for extension in extensions]
	for path in paths:
		if os.path.exists(path):
			if env["constants"]["platform"] == "mac":
				applescript = """/usr/bin/osascript<<END\ntell application "Finder"\nset desktop picture to POSIX file "%s"\nend tell\nEND"""
				subprocess.Popen(applescript % path.replace('"',r'\"'), shell=True)
			elif env["constants"]["platform"] == "win":
				ctypes.windll.user32.SystemParametersInfoA(20,0,path.encode(locale.getpreferredencoding()),0)
			else:
				subprocess.Popen(env["static"]["cwWallPaper_commandLine"] % path, shell=True)
			return [("replace","")]
	return [("messageBox", env["static"]["cwWallPaper_fileNotFoundMessage"] % "\n".join(paths))]
